package edu.pe.cayetano.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import edu.pe.cayetano.framework.Configuration;
import edu.pe.cayetano.framework.DAOException;
import edu.pe.cayetano.model.to.AlumnoTO;

public class AlumnoDAO  extends BaseDAO{

	public AlumnoDAO(Connection cnx) {
		super(cnx);
	}

	/**
	 * Retorna los datos del alumno 
	 * */
	public AlumnoTO getAlumno(int codigoAlumno) throws Exception{

		AlumnoTO 					alumnoTO	= null;
		PreparedStatement   		pstmt 		= null;
		ResultSet 					rs 			= null;
		String 						schema		= Configuration.getSchemaDB();
	
		try{
			StringBuffer query  = new StringBuffer();
			query.append("SELECT CODIGO_ALUMNO FROM "+schema+"ALUMNO WHERE CODIGO_USUARIO=?");
			System.out.println("[SECCD][AlumnoDAO][getAlumnosxCiclo]:query:"+query.toString());
			pstmt = getConnection().prepareStatement(query.toString());
			pstmt.setInt(1,codigoAlumno);
			rs=pstmt.executeQuery();
			if(rs.next()){
				alumnoTO=new AlumnoTO();
				alumnoTO.setCodigo(rs.getString(1));
			}
		}catch(Exception e){
			System.out.println("[SECCD][AlumnoDAO][getAlumno]:error generado por:"+e.getMessage());
			throw new DAOException(e.getMessage());
		}finally{
			try{
				rs.close();
				pstmt.close();
			}catch(Exception e){
				System.out.println("[SECCD][AlumnoDAO][getAlumno]:error generado por:"+e.getMessage());
			}
		}
		return alumnoTO;
	}
	
	/**
	 * Metodo que retorna el listado de alumnos por un ciclo 
	 * */
	public ArrayList<AlumnoTO> getAlumnosxCiclo(String ciclo) throws Exception{

		AlumnoTO					alumnoTO 	= null;
		ArrayList<AlumnoTO> 		lista		= new ArrayList<AlumnoTO>();
		PreparedStatement   		pstmt 		= null;
		ResultSet 					rs 			= null;
		String 						schema		= Configuration.getSchemaDB();
	
		try{
			StringBuffer query  = new StringBuffer();
			query.append("SELECT CODIGO_ALUMNO,NOMBRE_COMPLETO FROM "+schema+"V_ALUMNO WHERE CICLO_ID=?");
			
			System.out.println("[SECCD][AlumnoDAO][getAlumnosxCiclo]:query:"+query.toString());
			
			pstmt = getConnection().prepareStatement(query.toString());
			pstmt.setString(1,ciclo);
			rs=pstmt.executeQuery();

			while(rs.next()){
				alumnoTO=new AlumnoTO();
				alumnoTO.setCodigo(rs.getString(1));
				alumnoTO.setNombre(rs.getString(2));
				lista.add(alumnoTO);
			}
		}catch(Exception e){
			System.out.println("[SECCD][AlumnoDAO][getAlumnosxCiclo]:error generado por:"+e.getMessage());
			throw new DAOException(e.getMessage());
		}finally{
			try{
				rs.close();
				pstmt.close();
			}catch(Exception e){
				System.out.println("[SECCD][AlumnoDAO][getAlumnosxCiclo]:error generado por:"+e.getMessage());
			}
		}
		return lista;
	}
}
